package com.chenfengyao.gamereversi

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.MotionEvent
import android.view.WindowInsets
import android.view.WindowManager
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.chenfengyao.gamereversi.core.ChessPiece
import com.chenfengyao.gamereversi.databinding.ActivityMainBinding
import com.chenfengyao.gamereversi.util.repeatCollectOnStarted
import com.chenfengyao.gamereversi.ai.AIDifficulty

class MainActivity : AppCompatActivity() {

    private val mainViewModel: MainViewModel by viewModels()
    private val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        enableEdgeToEdge()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window.insetsController?.hide(WindowInsets.Side.all())

        setContentView(binding.root)

        binding.initViews() // 初始化View


        // 棋盘
        repeatCollectOnStarted(mainViewModel.referee.nextPlayerFlow) {
            if (it == ChessPiece.NONE) {
                return@repeatCollectOnStarted
            }
            binding.currentPlayerView.setBackgroundResource(
                when (it) {
                    ChessPiece.BLACK -> R.color.chess_piece_black
                    ChessPiece.WHITE -> R.color.chess_piece_white
                    else -> R.color.chess_piece_black
                }
            )

            if (mainViewModel.needAIPlay(it)) {
                // 让AI下棋
                val aiPlace = mainViewModel.useAIPlay(it)
                if (aiPlace.first >= 0 && aiPlace.second >= 0) {
                    binding.board.playChess(aiPlace.first, aiPlace.second)
                }
            }
        }

        // 分数
        repeatCollectOnStarted(mainViewModel.referee.scoreFlow) {
            binding.blackScoreTv.text = it[0].toString()
            binding.whiteScoreTv.text = it[1].toString()
        }

        // 游戏角色
        repeatCollectOnStarted(mainViewModel.blackPlayerIdentityFlow) { identity ->
            when (identity) {
                MainViewModel.PlayerIdentity.HUMAN -> binding.blackPlayerView.setImageDrawable(null)
                MainViewModel.PlayerIdentity.AI -> {
                    binding.blackPlayerView.setImageResource(R.drawable.baseline_flash_auto_24)
                    if (mainViewModel.referee.nextPlayer == ChessPiece.BLACK) {
                        val aiPlace = mainViewModel.useAIPlay(ChessPiece.BLACK)
                        if (aiPlace.first >= 0 && aiPlace.second >= 0) {
                            binding.board.playChess(aiPlace.first, aiPlace.second)
                        }
                    }
                }
            }
        }

        repeatCollectOnStarted(mainViewModel.whitePlayerIdentityFlow) { identity ->
            when (identity) {
                MainViewModel.PlayerIdentity.HUMAN -> binding.whitePlayerView.setImageDrawable(null)
                MainViewModel.PlayerIdentity.AI -> {
                    binding.whitePlayerView.setImageResource(R.drawable.baseline_flash_auto_24)
                    if (mainViewModel.referee.nextPlayer == ChessPiece.WHITE) {
                        val aiPlace = mainViewModel.useAIPlay(ChessPiece.WHITE)
                        if (aiPlace.first >= 0 && aiPlace.second >= 0) {
                            binding.board.playChess(aiPlace.first, aiPlace.second)
                        }
                    }
                }
            }
        }

        // Show spinner on current player icon instead of overlay
        repeatCollectOnStarted(mainViewModel.isThinkingFlow) {
            binding.currentThinkingSpinner.visibility = if (it) android.view.View.VISIBLE else android.view.View.GONE
        }

        // Global bottom panel was replaced by per-side difficulty rows.
        // Black difficulty buttons
        binding.btnBlackEasy.setOnClickListener { mainViewModel.setBlackDifficulty(AIDifficulty.EASY) }
        binding.btnBlackMedium.setOnClickListener { mainViewModel.setBlackDifficulty(AIDifficulty.MEDIUM) }
        binding.btnBlackHard.setOnClickListener { mainViewModel.setBlackDifficulty(AIDifficulty.HARD) }
        // Legacy strategy buttons (blue)
        binding.btnBlackLegacy.setOnClickListener { mainViewModel.setBlackEngineLegacy(true) }
        binding.btnWhiteLegacy.setOnClickListener { mainViewModel.setWhiteEngineLegacy(true) }

        // White difficulty buttons
        binding.btnWhiteEasy.setOnClickListener { mainViewModel.setWhiteDifficulty(AIDifficulty.EASY) }
        binding.btnWhiteMedium.setOnClickListener { mainViewModel.setWhiteDifficulty(AIDifficulty.MEDIUM) }
        binding.btnWhiteHard.setOnClickListener { mainViewModel.setWhiteDifficulty(AIDifficulty.HARD) }

        // Reflect selected difficulty visually per side
        repeatCollectOnStarted(mainViewModel.blackDifficultyFlow) {
            binding.btnBlackEasy.isSelected = it == AIDifficulty.EASY
            binding.btnBlackMedium.isSelected = it == AIDifficulty.MEDIUM
            binding.btnBlackHard.isSelected = it == AIDifficulty.HARD
        }
        repeatCollectOnStarted(mainViewModel.whiteDifficultyFlow) {
            binding.btnWhiteEasy.isSelected = it == AIDifficulty.EASY
            binding.btnWhiteMedium.isSelected = it == AIDifficulty.MEDIUM
            binding.btnWhiteHard.isSelected = it == AIDifficulty.HARD
        }
        repeatCollectOnStarted(mainViewModel.blackUseLegacyFlow) {
            binding.btnBlackLegacy.isSelected = it
        }
        repeatCollectOnStarted(mainViewModel.whiteUseLegacyFlow) {
            binding.btnWhiteLegacy.isSelected = it
        }

    }

    private fun ActivityMainBinding.initViews() {
        refreshView.setOnHoverListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_HOVER_ENTER -> {
                    refreshView.animate().translationZ(10f).scaleX(1.1f).scaleY(1.1f).start()
                }

                MotionEvent.ACTION_HOVER_EXIT -> {
                    refreshView.animate().translationZ(0f).scaleX(1f).scaleY(1f).start()
                }
            }
            true

        }

        blackPlayerView.setOnClickListener {
            mainViewModel.changePlayerIdentity(ChessPiece.BLACK)
        }

        whitePlayerView.setOnClickListener {
            mainViewModel.changePlayerIdentity(ChessPiece.WHITE)
        }

        refreshView.setOnClickListener {
            refreshIcon.rotation = 0F
            refreshIcon.animate().rotation(360f).start()

            mainViewModel.referee.init()
        }

        board.post {
            board.initBoard()
            board.initGame(mainViewModel.referee)
        }

        board.onCellClick = { x, y ->
            board.playChess(x, y)
        }
    }
}